package com.dpiinc.TechPage.pen.fragment
import android.Manifest
import android.Manifest.permission.BLUETOOTH_CONNECT
import android.Manifest.permission.BLUETOOTH_SCAN
import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.content.*
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.provider.Settings
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.dpiinc.TechPage.AIWriteApplication
import com.dpiinc.TechPage.R
import com.dpiinc.TechPage.pen.adapter.PenListAdapter
import com.dpiinc.TechPage.pen.dialog.ServiceHintDialog
import com.dpiinc.TechPage.room.PenDaoUtils
import com.dpiinc.TechPage.user.utils.ToastUtils
import com.dpiinc.TechPage.widget.CommDialog
import com.beiji.lib.pen.PenLog
import com.beiji.lib.pen.PenScanner
import com.beiji.lib.pen.model.PenInfo
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.Permission
import kotlinx.android.synthetic.main.fragment_pen_list.*


/**
 * 数码笔扫描Fragment
 * Created by X on 2018/6/14.
 */
class ScanPenFragment : Fragment() {
    private var isOpenGPS: MutableLiveData<Boolean> = MutableLiveData()
    private lateinit var adapter: PenListAdapter

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_pen_list, container, false)
    }

    override fun onResume() {
        super.onResume()
        if(isHasAlwaysPermission){
            activity?.finish()
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        openBluetooth()

        val penList = view.findViewById<RecyclerView>(R.id.pen_list)
        penList.layoutManager = LinearLayoutManager(context)
        penList.adapter = adapter
        penList.addItemDecoration(DividerItemDecoration(activity, DividerItemDecoration.VERTICAL).apply {
            setDrawable(ContextCompat.getDrawable(activity!!, R.drawable.connect_pen_list_divider_shape)!!)
        })
        val btnRescan = view.findViewById<TextView>(R.id.btn_rescan)
        btnRescan.setOnClickListener { restartScan() }


    }

    @SuppressLint("MissingPermission")
    fun openBluetooth() {
        val blueadapter = (context?.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter
        //val blueadapter = BluetoothAdapter.getDefaultAdapter()
        if (blueadapter == null) {
            ToastUtils.showCenterTip(context, getString(R.string.not_support_bluetooth))
        } else {
            if (blueadapter.isEnabled) {
                return
            } else {
       /*         Handler().postDelayed({
                    ServiceHintDialog.ShowDialog(context, resources.getString(R.string.service_dialog_title_hint),
                            resources.getString(R.string.service_dialog_msg_hint2))
                }, 200)*/
               // blueadapter.enable()
                val enabler = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
                startActivityForResult(enabler, 100)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        registerBluetoothStateReceiver()
    }

    override fun onDestroy() {
        super.onDestroy()
        unRegisterBluetoothStateReceiver()
    }
    /**
     * 注册蓝牙开启状态变更通知
     */
    fun registerBluetoothStateReceiver() {
        var intent = IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        context?.registerReceiver(receiver, intent);
    }

    /**
     * 取消注册蓝牙开启状态变更通知
     */
    fun unRegisterBluetoothStateReceiver() {
        if (receiver != null) {
            try {
                context?.unregisterReceiver(receiver)
            } catch (e: Exception ) {

            }
        }
    }

    private val receiver = object : BroadcastReceiver() {
        @Override
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.getAction();
            if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
                val state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
                ServiceHintDialog.dismissDialog()
                //case BluetoothAdapter.STATE_TURNING_ON
                //case BluetoothAdapter.STATE_TURNING_OFF:
                //case BluetoothAdapter.STATE_OFF:
            }
        }
    };
    @RequiresApi(Build.VERSION_CODES.S)
    val LOCATION_NEW = arrayOf(
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.ACCESS_COARSE_LOCATION,
        BLUETOOTH_CONNECT,
        BLUETOOTH_SCAN,
        Manifest.permission.BLUETOOTH_ADVERTISE
    )

    private fun requestLocationPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            AndPermission.with(this)
                .runtime()
                .permission(LOCATION_NEW)
                //拒绝一次之后的提示
                .rationale { context, _, executor ->
                    PenLog.e("rationale")
                    ServiceHintDialog.dismissDialog()
                    executor.execute()
                }
        } else {
            AndPermission.with(this)
                .runtime()
                .permission(Permission.Group.LOCATION)
                //拒绝一次之后的提示
                .rationale { context, _, executor ->
                    PenLog.e("rationale")
                    ServiceHintDialog.dismissDialog()
                    executor.execute()
                }
        }
                //申请被拒绝
                .onDenied { permissions ->
                    ServiceHintDialog.dismissDialog()
                    PenLog.e("onDenied")
                    //被拒绝，且选择了不再提醒之后，需要提示用户去设置页面手动打开
                    if (AndPermission.hasAlwaysDeniedPermission(context, permissions)) {
                        val builder = CommDialog.Builder()
                        builder.setMessage(getString(R.string.need_position_authority_real))
                                .setLeftButton(getString(R.string.need_authority_refuse), DialogInterface.OnClickListener { dialogInterface, _ ->
                                    dialogInterface.dismiss()
                                    activity?.finish()
                                })
                                .setRightButton(getString(R.string.need_authority_ok2), DialogInterface.OnClickListener { dialogInterface, _ ->
                                    dialogInterface.dismiss()
                                    AndPermission.with(this)
                                            .runtime()
                                            .setting()
                                            .onComeback {
                                                isHasAlwaysPermission = true
                                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                                                    if (!AndPermission.hasPermissions(this, LOCATION_NEW)) {
                                                        activity?.finish()
                                                        isHasAlwaysPermission = false
                                                    }
                                                } else {
                                                    if (!AndPermission.hasPermissions(this, Permission.Group.LOCATION)) {
                                                        activity?.finish()
                                                        isHasAlwaysPermission = false
                                                    }
                                                }
                                            }
                                            .start()
                                })
                        builder.build().show(activity!!.supportFragmentManager)
                    }else{
                        activity?.finish()
                    }
                }
                .onGranted { _ ->
                    ServiceHintDialog.dismissDialog()
                    PenScanner.instance.startScan(scanPenCallBack, SCAN_TIMEOUT)
                }
                .start()
    }
    private var isHasAlwaysPermission = false
    private var scanPenCallBack = object : PenScanner.ScanPenCallBack {
        override fun onPenFound(pen: PenInfo) {
            Log.i(TAG, "onPenFound: ${pen.toString()}")
            Log.i(TAG, pen.macAddress)
            if (isDetached) {
                return
            }
            scan_animation_view.visibility = View.GONE
            no_pen_found_layout.visibility = View.GONE
            pen_list.visibility = View.VISIBLE
            activity?.let {
                pen.name = PenDaoUtils.getPenName(it, pen.name, pen.macAddress)
            }
            if (adapter.addPen(pen)) {

            }
        }

        override fun onTimeOut() {
            if (!adapter.hasPen()) {
                scan_animation_view.visibility = View.GONE
                no_pen_found_layout.visibility = View.VISIBLE
                pen_list.visibility = View.GONE
            }
        }

    }


    private fun restartScan() {
        PenScanner.instance.startScan(scanPenCallBack, SCAN_TIMEOUT)
        scan_animation_view.visibility = View.VISIBLE
        no_pen_found_layout.visibility = View.GONE
        pen_list.visibility = View.GONE
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        isOpenGPS.observe(this, Observer {
            if (it!!) {
                Log.i(TAG, "onAttach: observe")
                PenScanner.instance.startScan(scanPenCallBack, SCAN_TIMEOUT)
            }
        })
        var hasPermissions = false
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
             hasPermissions = AndPermission.hasPermissions(this, LOCATION_NEW)
        } else {
            hasPermissions = AndPermission.hasPermissions(this, Permission.Group.LOCATION)
        }
        if (hasPermissions) {
            //执行业务
            if (checkGPSIsOpen()) {
                PenScanner.instance.startScan(scanPenCallBack, SCAN_TIMEOUT)
            } else {

                Handler().postDelayed({
                    if (showHintDialog){
                        ServiceHintDialog.ShowDialog(context, resources.getString(R.string.service_dialog_title_hint),
                                resources.getString(R.string.service_dialog_msg_hint2))
                    }
                }, 250)

                showHintDialog = true;
                openGPS()
            }

        } else {

            Handler().postDelayed({
                if (showHintDialog){
                    ServiceHintDialog.ShowDialog(context, resources.getString(R.string.service_dialog_title_hint),
                            resources.getString(R.string.service_dialog_msg_hint2))
                }
            }, 250)

            requestLocationPermissions()

        }

        adapter = PenListAdapter(context!!)

        if (context is OnListFragmentInteractionListener) {
            adapter.setOnItemInteractionListener(context)
        } else {
            throw RuntimeException(context.toString() + " must implement OnListFragmentInteractionListener")
        }

    }


    private var showHintDialog = true

    override fun onDetach() {
        Log.i(TAG, "onDetach: ")
        PenScanner.instance.stopScan()
        super.onDetach()
//        adapter.setOnItemInteractionListener(null)
    }

    interface OnListFragmentInteractionListener {
        fun onListFragmentInteraction(pen: PenInfo)
    }

    private fun openGPS() {
//        val lm = activity!!.getSystemService(LOCATION_SERVICE) as LocationManager
//        val ok = lm.isProviderEnabled(LocationManager.GPS_PROVIDER)
//        if (!ok) {
//            val builder = CommDialog.Builder()
//            builder.setMessage(getString(R.string.open_location_service))
//                    .setLeftButton(getString(R.string.cancel), DialogInterface.OnClickListener { dialogInterface, _ ->
//                        dialogInterface.dismiss()
//                        activity?.finish()
//                    })
//                    .setRightButton(getString(R.string.open), DialogInterface.OnClickListener { dialogInterface, _ ->
//                        dialogInterface.dismiss()
//                        val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
//                        startActivityForResult(intent, 887)
//                        dialogInterface.dismiss()
//                    })
//            builder.build().show(activity?.supportFragmentManager)
//        }
        val builder = CommDialog.Builder()
        builder.setMessage(getString(R.string.open_location_service))
                .setLeftButton(getString(R.string.cancel), DialogInterface.OnClickListener { dialogInterface, _ ->
                    dialogInterface.dismiss()
                    ServiceHintDialog.dismissDialog()
                    activity?.finish()
                })
                .setRightButton(getString(R.string.open), DialogInterface.OnClickListener { dialogInterface, _ ->
                    dialogInterface.dismiss()
                    ServiceHintDialog.dismissDialog()
                    val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                    startActivityForResult(intent, 887)
                    dialogInterface.dismiss()
                })
        builder.build().show(activity!!.supportFragmentManager)
    }

    private fun checkGPSIsOpen(): Boolean {
        var locationMode = 0
        var locationProviders: String
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                locationMode = Settings.Secure.getInt(AIWriteApplication.instance().contentResolver, Settings.Secure.LOCATION_MODE)
            } catch (e: Exception) {
                e.printStackTrace()
                return false
            }
            return locationMode != Settings.Secure.LOCATION_MODE_OFF
        } else {
            locationProviders = Settings.Secure.getString(AIWriteApplication.instance().contentResolver, Settings.Secure.LOCATION_PROVIDERS_ALLOWED)
            return !TextUtils.isEmpty(locationProviders)
        }
    }

    companion object {
        val TAG: String = ScanPenFragment::class.java.simpleName
        private const val SCAN_TIMEOUT = 60 // 60秒超时

        fun newInstance(): ScanPenFragment {
            return ScanPenFragment()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 887 && resultCode == 0) {
            isOpenGPS.value = true
        }
    }
}
